package org.jeecg.modules.fund.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.fund.entity.FundLibrary;
import org.jeecg.modules.fund.entity.FundList;
import org.jeecg.modules.fund.entity.FundOptional;
import org.jeecg.modules.fund.entity.FundOptionalGroup;
import org.jeecg.modules.fund.mapper.FundHoldMapper;
import org.jeecg.modules.fund.mapper.FundLibraryMapper;
import org.jeecg.modules.fund.mapper.FundOptionalMapper;
import org.jeecg.modules.fund.service.IFundLibraryService;
import org.jeecg.modules.fund.service.IFundOptionalGroupService;
import org.jeecg.modules.fund.service.IFundOptionalService;
import org.jeecg.modules.fund.service.IFundValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "基金自选")
@RequestMapping("/sys/fund/optional")
@Slf4j
public class FundOptionalController {
    @Autowired
    private IFundOptionalService optionalService;
    @Autowired
    private FundOptionalMapper fundOptionalMapper;
    @Autowired
    private FundHoldMapper fundHoldMapper;
    @Autowired
    private IFundValueService fundValueService;
    @Autowired
    private IFundLibraryService fundLibraryService;
    @Autowired
    private IFundOptionalGroupService fundOptionalGroupService;
    @Autowired
    private FundLibraryMapper fundLibraryMapper;

    /**
     * 添加自选
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<FundOptional> add(@RequestBody FundOptional optional) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        optional.setUserId(sysUser.getId());
        return optionalService.add(optional);
    }

    /**
     * 移动分组
     * @param optionalList
     * @return
     */
    @RequestMapping(value = "/moveGroup", method = RequestMethod.POST)
    public Result<FundOptional> moveGroup(@RequestBody List<FundOptional> optionalList) {
        List<FundOptional> paramList = new ArrayList<>();
        for (FundOptional item : optionalList){
            FundOptional optional = new FundOptional();
            optional.setId(item.getId());
            optional.setGroupId(item.getGroupId());

            paramList.add(optional);
        }
        if(!paramList.isEmpty()) {
            optionalService.updateBatchById(paramList);
        }
        return Result.OK("分组成功");
    }

    /**
     * 批量更新
     * @param optionalList
     * @return
     */
    @RequestMapping(value = "/batchUpdate", method = RequestMethod.POST)
    public Result<FundOptional> batchUpdate(@RequestBody List<FundOptional> optionalList) {
        optionalService.updateBatchById(optionalList);
        return Result.OK("更新成功");
    }


    /**
     * 删除分组
     * @param groupList
     * @return
     */
    @RequestMapping(value = "/deleteGroup", method = RequestMethod.POST)
    public Result<String> deleteGroup(@RequestBody List<FundOptionalGroup> groupList) {
        // 批量删除
        fundOptionalGroupService.removeBatchByIds(groupList);
        // 删除成功后需要其底下分组的数据设置为空
        for(FundOptionalGroup group : groupList){
            optionalService.update(new LambdaUpdateWrapper<FundOptional>()
                    .set(FundOptional::getGroupId,null)
                    .eq(FundOptional::getGroupId,group.getId()));
        }
        return Result.OK("删除成功");
    }

    /**
     * 批量更新分组
     * @param groupList
     * @return
     */
    @RequestMapping(value = "/batchUpdateGroup", method = RequestMethod.POST)
    public Result<String> batchUpdateGroup(@RequestBody List<FundOptionalGroup> groupList) {
        // 批量删除
        fundOptionalGroupService.updateBatchById(groupList);
        return Result.OK("更新成功");
    }

    /**
     * 取消自选
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public Result<String> delete(@RequestParam("id")String id) {
        return optionalService.delete(id);
    }

    /**
     * 批量删除
     * @param optionalList
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result<FundOptional> batchDelete(@RequestBody List<FundOptional> optionalList) {
        optionalService.removeBatchByIds(optionalList);
        return Result.OK("删除成功");
    }

    /**
     * 提示统计
     * @return
     */
    @RequestMapping(value = "/tipCount", method = RequestMethod.GET)
    public Result<List<Map<String,Object>>> tipCount() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<Map<String,Object>> res = fundOptionalMapper.tipCount(sysUser.getId());
        return Result.OK(res);
    }

    /**
     * 自选分页
     *
     * @param fundLibrary
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<Map<String, Object>>> queryPageList(FundLibrary fundLibrary,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        fundLibrary.setUserId(sysUser.getId());

        // 分页设置
        Page<FundLibrary> page = new Page<>(pageNo, pageSize);
        // 分页
        IPage<Map<String, Object>> pageList = fundOptionalMapper.selectPageVo(page, fundLibrary);
        return Result.OK(pageList);
    }

    /**
     * 获取趋势线的值(自选)
     *
     * @param fundId
     * @param str
     * @return
     */
    @RequestMapping(value = "/queryLine", method = RequestMethod.GET)
    public Result<List<Map<String, Object>>> queryLine(@RequestParam(name = "fundId", required = true) String fundId,
                                                       @RequestParam(name = "str", required = true) String str,
                                                       @RequestParam(name = "lineType", required = true) String lineType) {
        FundLibrary library = fundLibraryService.getById(fundId);
        if (library == null) {
            return Result.error("基金不存在");
        }
        // 起始日期
        String startDate;
        // 获取表名
        String tableName = fundValueService.tableName(library.getCode());
        // 格式化日期
        if ("近1月".equals(str)) {
            startDate = DateUtil.format(DateUtil.offsetDay(new Date(), -29), "yyyy-MM-dd");
        } else if ("近3月".equals(str)) {
            startDate = DateUtil.format(DateUtil.offsetDay(new Date(), -89), "yyyy-MM-dd");
        } else if ("近6月".equals(str)) {
            startDate = DateUtil.format(DateUtil.offsetDay(new Date(), -179), "yyyy-MM-dd");
        } else if ("近1年".equals(str)) {
            startDate = DateUtil.format(DateUtil.offsetDay(new Date(), -365), "yyyy-MM-dd");
        } else if ("近3年".equals(str)) {
            startDate = DateUtil.format(DateUtil.offsetDay(new Date(), -1095), "yyyy-MM-dd");
        } else if ("近5年".equals(str)) {
            startDate = DateUtil.format(DateUtil.offsetDay(new Date(), -1825), "yyyy-MM-dd");
        } else if ("今年来".equals(str)) {
            startDate = DateUtil.format(new Date(), "yyyy") + "-01-01";
        } else {
            // 成立来
            startDate = null;
        }
        // 结果集
        List<Map<String, Object>> data = new ArrayList<>();
        if(lineType.equals("optional")) {
            data = fundOptionalMapper.findOptionalValueList(tableName, fundId, startDate, DateUtil.format(new Date(),"yyyy-MM-dd"));
        } else if (lineType.equals("hold")){
            data = fundHoldMapper.findHoldValueList(tableName, fundId, startDate, DateUtil.format(new Date(),"yyyy-MM-dd"));
        } else {
            data = fundLibraryMapper.findValueList(tableName, fundId, startDate, DateUtil.format(new Date(),"yyyy-MM-dd"));
        }
        return Result.OK(data);
    }

    @RequestMapping(value = "/queryWave", method = RequestMethod.GET)
    public Result<List<Dict>> queryWave(@RequestParam(name = "fundId", required = true) String fundId) {
        return optionalService.queryWave(fundId);
    }

    /**
     * 自选详情
     * @param optId
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public Result<FundOptional> detail(@RequestParam(name = "optId", required = true) String optId) {
        FundOptional optional = optionalService.getById(optId);
        return Result.ok(optional);
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result<FundOptional> update(@RequestBody FundOptional optional) {
        optionalService.updateById(optional);
        return Result.ok("更新成功");
    }

    /**
     * 自选分组
     * @param
     * @return
     */
    @RequestMapping(value = "/groupList", method = RequestMethod.GET)
    public Result<List<FundOptionalGroup>> groupList() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<FundOptionalGroup> list = fundOptionalGroupService
                .list(new LambdaQueryWrapper<FundOptionalGroup>()
                .eq(FundOptionalGroup::getUserId,sysUser.getId())
                .orderByAsc(FundOptionalGroup::getSort));
        return Result.OK(list);
    }

    @RequestMapping(value = "/addGroup", method = RequestMethod.POST)
    public Result<FundOptionalGroup> addGroup(@RequestBody FundOptionalGroup group) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        FundOptionalGroup fundOptionalGroup = fundOptionalGroupService.getOne(new LambdaQueryWrapper<FundOptionalGroup>()
                .eq(FundOptionalGroup::getUserId,sysUser.getId())
                .eq(FundOptionalGroup::getName,group.getName()));
        if(fundOptionalGroup != null) {
            return Result.error("组名重复");
        }

        // 设置用户
        group.setUserId(sysUser.getId());
        // 保存
        fundOptionalGroupService.save(group);
        return Result.ok(group);
    }
}
